package com.leo.oplayer.filter;

import com.leo.oplayer.model.ConDetail;
import com.leo.oplayer.service.ContactService;
import com.leo.oplayer.util.Constancts;
import com.leo.oplayer.util.DateUtil;
import com.leo.oplayer.util.PersonUtil;

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;

public class SmsObserver extends ContentObserver {
	
	public static final String TYPE_RECEIVE = "1";
	
	public static final String TYPE_SEND = "2";
	
	private static final String TAG = "SmsObserver";
	
	private Context context;
	
	private ContactService contactService;
	
	/** 
	 * person - 联系人列表里中的联系人id
	 * read - 是否阅读
	 * status - 状态
	 * type - 类型 1是接收到的，2是发出的
	 * body - 内容
	 */
	private static final String[] SMS_PROJECTION = new String[] {
	       "address","person","date","read","status","type","body",
	    };

	public SmsObserver(Context context,Handler handler) {
		super(handler);		
		this.context = context;	
		contactService = new ContactService(context);
	}
	
	public void onChange (boolean selfChange) {
		ContentResolver content = context.getContentResolver();
		String orderBy = "date desc";
        Cursor cursor = content.query(Uri.parse(Constancts.URI_SMS), SMS_PROJECTION, null, null, orderBy);
        if(cursor != null && cursor.moveToFirst()){
        	//TODO:只是记录日志，测试完要删掉-----begin
        	StringBuffer sb = new StringBuffer("");        
    		for(int i= 0; i<SMS_PROJECTION.length;i++){
        		sb.append(cursor.getColumnName(i)+":").append(cursor.getString(i)).append("#");
        	}
        	Log.i(TAG, "sms:"+sb.toString());
        	
        	
        	
        	//类型-发送或接收
        	String type = cursor.getString(cursor.getColumnIndex("type"));
        	String date = DateUtil.getStringDate(cursor.getLong(cursor.getColumnIndex("date")), Constancts.TIME_FORMAT_SAVE);
        	//用户id
        	String person = cursor.getString(cursor.getColumnIndex("person"));
        	String address = cursor.getString(cursor.getColumnIndex("address"));
        	if(person == null){
        		person = PersonUtil.findIdByNumber(context, address);
        	}

        	//联系人存在才同步到统计表        	
        	if(person != null){
        		//组织通讯详情
        		ConDetail detail = new ConDetail();
        		detail.setConStartTime(date);
        		
        		if(type.equals(TYPE_RECEIVE)){
        			Log.i(TAG, "#sync receive sms");
        			contactService.syncCommunicationStat(person, detail,Constancts.MSG_IN);
        		}else if(type.equals(TYPE_SEND)){
        			Log.i(TAG,"#sync send sms");
        			contactService.syncCommunicationStat(person, detail,Constancts.MSG_OUT);
        		}
        	}
    	}
	}
}
